package com.ytsakura.blog.dao;

import com.ytsakura.blog.pojo.Blog;
import com.ytsakura.blog.pojo.User;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;


@Service
public interface BlogRepository extends JpaRepository<Blog,Long>, JpaSpecificationExecutor<Blog> {
    Page<Blog> findBlogsByUser(Pageable pageable, User user);

    @Query("select function('date_format',b.updateTime,'%Y') as year from Blog b group by function('date_format',b.updateTime,'%Y') order by year DESC " )
    List<String> findGroupYear();

    @Query("select b from Blog b where function('date_format',b.updateTime,'%Y') = ?1")
    List<Blog> findByYear(String year);

    @Query("select b from Blog b where b.recommend = true and b.published = true")
    List<Blog> findTop(Pageable pageable);

    @Query("select b from Blog b where b.title like ?1 or b.content like ?1 and b.published = true")
    Page<Blog> findByQuery(String query,Pageable pageable);

    @Query("select b from Blog b where b.title like ?1 or b.content like ?1 and b.user = ?2")
    Page<Blog> findByUserQuery(String query,User user,Pageable pageable);

    @Transactional
    @Modifying
    @Query("update Blog b set b.views = b.views+1 where  b.id = ?1")
    int updateViews(Long id);

    Page<Blog> findAllByPublished(boolean published, Pageable pageable);

}
